package com.gxy.learn.thread.example;

import java.util.concurrent.Semaphore;

/**
 * @description: 信号量
 * 默认非公平，可以设置公平（公平就是排队执行）
 * 场景：限流、车道、收费站
 * @author: gaoxueyong
 * @Date: 2022/11/10 14:59
 */
public class SemaphoreTest {

    public static void main(String[] args) {
//        test1();
        test();
    }


    public static void test(){
        Semaphore semaphore = new Semaphore(1,true);
        for(int i=0;i<100;i++){
            int finalI = i;
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println("T"+ finalI +" running......");
                    Thread.sleep(2000);
                    System.out.println("T"+finalI+" ending......");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }
            }).start();
        }
    }
    public static void test1(){
//        默认不公平 设置一个信号量，只能有一个执行
        Semaphore semaphore = new Semaphore(1);
//        同时只能有两个线程执行
//        Semaphore semaphore = new Semaphore(2);
//        两个信号量，公平
//        Semaphore semaphore = new Semaphore(2,true);


        new Thread(() -> {
            try {
//                请求 阻塞
                semaphore.acquire();
                System.out.println("T1 running......");
                Thread.sleep(2000);
                System.out.println("T1 ending......");

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
//                释放
                semaphore.release();
            }
        }, "t1").start();
        new Thread(() -> {
            try {
//                请求 阻塞
                semaphore.acquire();
                System.out.println("T2 running......");
                Thread.sleep(2000);
                System.out.println("T2 ending......");

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
//                释放
                semaphore.release();
            }
        }, "t2").start();
    }
}
